/*
 * Funny Language - a free style programming language.
 * Copyright (C) 2015 by fanguangping (fanguangping@163.com)
 * write.c
 */

#include <stdio.h>
#include "../basic/operator.h"

// (print x y z ...)
Cell* op_print(Scheme *sc) {
	Cell *x;

	for (x = sc->args; x != G_NIL; x = cdr(x)) {
		printf("%s", cell2str(sc, car(x)));
	}

	sc->returnValue = G_TRUE;
	return pop_callstack(sc);
}

// (print-line x y z ...)
Cell* op_print_line(Scheme *sc) {
	Cell *x;

	for (x = sc->args; x != G_NIL; x = cdr(x)) {
		printf("%s", cell2str(sc, car(x)));
	}
	printf("\n");

	sc->returnValue = G_TRUE;
	return pop_callstack(sc);
}

// (error x y z ...)
Cell* op_err(Scheme *sc) {
	Cell *x;

	if (!type_of(sc, car(sc->args), STRING_TYPE)) {
		sc->args = cons(sc, make_string(sc, " -- "), sc->args);
		set_immutable(sc->args);
	}
	fprintf(stderr, "Error: ");
	fprintf(stderr, car(sc->args)->_string);
	sc->args = cdr(sc->args);

	for (x = sc->args; x != G_NIL; x = cdr(x)) {
		fprintf(stderr, cell2str(sc, car(x)));
	}
	fprintf(stderr, "\n");

	sc->returnValue = G_TRUE;
	return pop_callstack(sc);
}

void init_write_operators(Scheme *sc) {
	ADD_OPERATOR(sc, "print", print);
	ADD_OPERATOR(sc, "print-line", print_line);
	ADD_OPERATOR(sc, "error", err);
}

